//
//  AlbumViewController.swift
//  AutoPrint
//
//  Created by David on 2017/1/20.
//  Copyright © 2017年 fatcat. All rights reserved.
//

import UIKit
import Photos

protocol AlbumBackCleanCachesDelegate {
    func navigationBackFrom(albumViewController: AlbumViewController)
}

class AlbumViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UDCheckBoxDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{

    var delegate: AlbumBackCleanCachesDelegate?
    
    let DOCUMENT_PATH = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! // 沙盒路径
    let CACHES_PATH = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
    var photoAssert: PHFetchResult?
    var imageAry: [UIImage?]?
    var collectionView: UICollectionView!
    var itemWidth: CGFloat!
    
    var selectedIndex:[Int] = []
    var submitBtn: UIBarButtonItem!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.groupTableViewBackgroundColor()
        title = "手机相册"
        
        submitBtn = UIBarButtonItem(title: "上传", style: .Plain, target: self, action: #selector(AlbumViewController.submit))
        submitBtn.enabled = false
        navigationItem.rightBarButtonItem = submitBtn
        
        
        
        itemWidth = (view.frame.width - 32)/4 - 8
        
        let collectLayout = UICollectionViewFlowLayout()
        collectLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        collectLayout.minimumInteritemSpacing = 8
        collectLayout.scrollDirection = .Vertical
        
        collectionView = UICollectionView(frame: CGRect(x: 16, y: 8, width: view.frame.width - 32, height: view.frame.height - 16), collectionViewLayout: collectLayout)
        
        collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "assert")
        collectionView.backgroundColor = UIColor.groupTableViewBackgroundColor()
        collectionView.alwaysBounceVertical = true
        collectionView.delegate = self
        collectionView.dataSource = self
        view.addSubview(collectionView)
        
        PHPhotoLibrary.requestAuthorization { (status) in
            if status == PHAuthorizationStatus.Authorized {
                self.refreshList()
            }
        }

        
        _ = try? NSFileManager.defaultManager().createDirectoryAtPath("\(CACHES_PATH)/photo", withIntermediateDirectories: true, attributes: nil)
//        if imageAry?.count <= 0 {
//            NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(AlbumViewController.timer), userInfo: nil, repeats: true)
//        }
        
        
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        refreshList()
        
    }
    
    func refreshList(){
        photoAssert = PHAsset.fetchAssetsWithMediaType(.Image, options: nil)
        
        if photoAssert != nil{
            imageAry = []
            photoAssert!.enumerateObjectsUsingBlock { (ass:AnyObject, i:Int, _:UnsafeMutablePointer<ObjCBool>) in
                let assRes = ass as! PHAsset
                PHImageManager.defaultManager().requestImageForAsset(assRes, targetSize: CGSize(), contentMode: PHImageContentMode.Default, options: nil, resultHandler: { (result:UIImage?, info:[NSObject : AnyObject]?) in
                    
                    self.imageAry?.append(result)
                    if i == self.photoAssert!.count - 1 {
                        self.imageAry = self.imageAry?.reverse()
                        dispatch_async(dispatch_get_main_queue(), {
                            self.collectionView.reloadData()
                        })
                    }
                    
                })
            }
        }
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if imageAry != nil {
            return imageAry!.count + 1
        }
        return 1
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("assert", forIndexPath: indexPath)
        let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height))
        if indexPath.row == 0{
            imgView.backgroundColor = UIColor.lightGrayColor()
            imgView.image = UIImage(named: "camera")
            cell.addSubview(imgView)
        }else {
            if imageAry != nil {
                if imageAry!.count > 0{
                    imgView.image = imageAry![indexPath.row-1]
                    imgView.contentMode = .ScaleAspectFill
                    imgView.layer.masksToBounds = true
                    cell.addSubview(imgView)
                    
                    let checkbox = UDCheckBox(point: CGPoint(x: cell.frame.width - 26, y: cell.frame.height - 26), id: indexPath.row - 1)
                    checkbox.delegate = self
                    
                    checkbox.checkedImage = UIImage(named: "checked")
                    checkbox.uncheckedImage = UIImage(named: "unchecked")
                    cell.addSubview(checkbox)
                }
            }
        }
        
        
        return cell
    }
    
    func checkBoxDidUpdate(checkbox: UDCheckBox) {
        if checkbox.checked {
            if selectedIndex.count < 9{
                selectedIndex.append(checkbox.id)
            }else{
                checkbox.goUnchecked()
                let alert = UIAlertController(title: "最多可以上传9个文件", message: nil, preferredStyle: .Alert)
                alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
                presentViewController(alert, animated: true, completion: nil)
                
            }
            
        }else{
            
            selectedIndex.removeAtIndex((selectedIndex.indexOf(checkbox.id)?.advancedBy(0))!)
        }
        
        if selectedIndex.count > 0 && selectedIndex.count <= 9{
            submitBtn.enabled = true
            submitBtn.title = "上传(\(selectedIndex.count)/9)"
        }else{
            submitBtn.title = "上传"
            submitBtn.enabled = false
        }
        
        print(selectedIndex)
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == 0{
            
            let picker = UIImagePickerController()
            picker.delegate = self
            if UIImagePickerController.isCameraDeviceAvailable(.Rear) || UIImagePickerController.isCameraDeviceAvailable(.Front) {
                picker.sourceType = .Camera
                presentViewController(picker, animated: true, completion: nil)
            }else{
                let alert = UIAlertController(title: "相机不可用", message: nil, preferredStyle: .Alert)
                alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
                presentViewController(alert, animated: true, completion: nil)
            }
        }else{
            if imageAry != nil {
                if imageAry!.count > 0{
                    hidesBottomBarWhenPushed = true
                    
                    let ass = photoAssert?.objectAtIndex(self.imageAry!.count - indexPath.row) as! PHAsset
                    PHImageManager.defaultManager().requestImageDataForAsset(ass, options: nil, resultHandler: { (data:NSData?, tempName:String?, orin:UIImageOrientation, info:[NSObject : AnyObject]?) in
                        
                        if data != nil {
                            let formater = NSDateFormatter()
                            formater.dateFormat = "yyyyMMddHHmmss"
                            let filetype = tempName?.componentsSeparatedByString(".").last
                            if filetype != nil {
                                let filename = "\(formater.stringFromDate(NSDate())).\(filetype!)"
                                let filepath = "\(self.CACHES_PATH)/photo/\(filename)"
                                print(filepath)
                                data?.writeToFile(filepath, atomically: true)
                                self.navigationController?.pushViewController(ImagePreViewController(named: filename, localImg: self.imageAry![indexPath.row - 1], localFilePath: filepath), animated: true)
                                
                            }
                            
                            
                        }
                        
                    })
                    
                }
            }
            
            
        }
    }
    
    func submit(){
        if selectedIndex.count > 0 && selectedIndex.count <= 9{
            if imageAry != nil {
                if imageAry!.count > 0{
                    hidesBottomBarWhenPushed = true
                    
                    var fileToSubmit:[UDFile] = []
                    
                    for i in 0..<selectedIndex.count {
                        let ass = photoAssert?.objectAtIndex(imageAry!.count - selectedIndex[i] - 1) as! PHAsset
                        PHImageManager.defaultManager().requestImageDataForAsset(ass, options: nil, resultHandler: { (data:NSData?, tempName:String?, orin:UIImageOrientation, info:[NSObject : AnyObject]?) in
                            
                            if data != nil {
                                let formater = NSDateFormatter()
                                formater.dateFormat = "yyyyMMddHHmmss"
                                let filetype = tempName?.componentsSeparatedByString(".").last
                                if filetype != nil {
                                    let filename = "\(formater.stringFromDate(NSDate()))-\(i).\(filetype!)"
                                    let filepath = "\(self.CACHES_PATH)/photo/\(filename)"
                                    //print(filepath)
                                    data?.writeToFile(filepath, atomically: true)
                                    
                                    let sizeToShow = Fatcat.getFileSize(filepath)
                                    if sizeToShow != nil {
                                        fileToSubmit.append(UDFile(filePath: filepath, fileName: filename, fileSize: sizeToShow, fileMD5: nil))
                                    }
                                    
                                    
                                    
                                    
                                    if i == self.selectedIndex.count - 1{
                                        let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                                        
                                        self.navigationController?.pushViewController(FileReadyViewController(files: fileToSubmit, step0VC: appdelegate.firstVC!), animated: true)
                                    }
                                    
                                }
                                
                                
                            }
                            
                        })
                    }
                    
                    
                    
                }
            }
        }
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//        print(info)
        dispatch_async(dispatch_get_main_queue()) { 
            picker.dismissViewControllerAnimated(true, completion: nil)
        }
        
//        picker.dismissViewControllerAnimated(true) {
//            self.showNext = true
//        }
        let image = info["UIImagePickerControllerOriginalImage"] as? UIImage
        if image != nil {
            UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
            var filename: String?
            var filepath: String?
            let data = UIImageJPEGRepresentation(image!, 1)
            if data != nil {
                let formater = NSDateFormatter()
                formater.dateFormat = "yyyyMMddHHmmss"
                filename = "\(formater.stringFromDate(NSDate())).jpg"
                filepath = "\(self.CACHES_PATH)/photo/\(filename!)"
                print(filepath)
                data?.writeToFile(filepath!, atomically: true)
            }
            hidesBottomBarWhenPushed = true
            
            dispatch_async(dispatch_get_main_queue(), {
                self.navigationController?.pushViewController(ImagePreViewController(named: filename, localImg: image, localFilePath: filepath), animated: true)
            })
            
            
            
            
            
        }

    }
    
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        print("album disappeared")
        
        delegate?.navigationBackFrom(self)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
